// websocket连接管理
import { ref, onMounted, onUnmounted } from 'vue'

export function useWebSocket() {
  const ws = ref(null)

  const connect = () => {
    ws.value = new WebSocket('ws://your-websocket-server')

    ws.value.onopen = () => {
      console.log('WebSocket连接成功')
    }

    ws.value.onmessage = (event) => {
      const message = JSON.parse(event.data)
      // 处理接收到的消息
      receiveMsg(message)
    }

    ws.value.onerror = (error) => {
      console.error('WebSocket错误:', error)
    }

    ws.value.onclose = () => {
      console.log('WebSocket连接关闭')
      // 可以在这里实现重连逻辑
    }
  }

  const sendMsg = (message) => {
    if (ws.value && ws.value.readyState === WebSocket.OPEN) {
      ws.value.send(JSON.stringify(message))
    }
  }

  const receiveMsg = (message) => {
    // 处理接收到的消息
    messages.value.push({
      type: 'receive',
      ...message,
    })
  }

  onMounted(() => {
    connect()
  })

  onUnmounted(() => {
    if (ws.value) {
      ws.value.close()
    }
  })

  return {
    sendMsg,
    receiveMsg,
  }
}
